package com.link.server.ws.handle.impl;

import com.link.common.packet.RequestOperate;
import com.link.common.packet.ResponseOperate;
import com.link.common.packet.recv.LoginPacket;
import com.link.common.packet.resp.LoginPacketResp;
import com.link.common.packet.resp.SimplePacketResp;
import com.link.database.entity.DBAccount;
import com.link.database.service.DBAccountService;
import com.link.server.ws.handle.HandleComponent;
import com.link.server.ws.handle.Handler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import jakarta.annotation.Resource;

import java.util.UUID;


@HandleComponent(RequestOperate.LOGIN)

public class LoginHandle implements Handler {
    @Resource
    private DBAccountService dbAccountService;

    @Override
    public   void invoke(RequestOperate operate, ByteBuf packet, ChannelHandlerContext ctx) throws  Exception{
        LoginPacket loginPacket = LoginPacket.fromBinary(packet);

        DBAccount account = dbAccountService.selectByUsername(loginPacket.username() );


        var verificationCode=ctx.channel().attr(Handler.VERIFICATION_CODE_KEY).get();
        if(verificationCode==null){
            this.send(ctx,SimplePacketResp.response(ctx,ResponseOperate.SEND_VERIFICATION_CODE, (short) 404));
             return ;
        }
        if (account != null) {
            if(verificationCode.equals(loginPacket.password())){

                var token= UUID.randomUUID().toString();
                ctx.channel().attr(Handler.ACCOUNT_KEY).set(account);
                LoginPacketResp loginPacketResp = new LoginPacketResp(true,true, account.isAdult(),token);
                ctx.channel().attr(  Handler.TOKEN_KEY).set(token);


                this.send(ctx,loginPacketResp.toBinary(ctx));


            }else{
                LoginPacketResp loginPacketResp = new LoginPacketResp(true,false, account.isAdult(),"");

                this.send(ctx,loginPacketResp.toBinary(ctx));

            }


        }  else{
            LoginPacketResp loginPacketResp = new LoginPacketResp(false,false, false,"");

            this.send(ctx,loginPacketResp.toBinary(ctx));



        }

    }

}
